package com.bj58.mis.apm.server.kylin.controller;

import com.bj58.mis.apm.server.kylin.service.IKylinAnalysisService;
import com.bj58.mis.apm.server.kylin.service.IZipFileService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/kylin")
public class KylinZipFileController {

    Log log = LogFactory.getLog(KylinZipFileController.class);

    @Resource
    private IKylinAnalysisService kylinAnalysis;
    @Resource
    private IZipFileService zipFileService;

    private final String basepath = "d:\\temp\\";

    @ResponseBody
    @RequestMapping("/check")
    public String check(HttpServletRequest req){
        Map<String, Object> params = new HashMap<>();
        params.put("remoteIp",req.getRemoteAddr());
        params.put("remoteHost",req.getRemoteHost());
        try {
            Date last = zipFileService.selectZipFile(params);
            if (last == null) {
                return "1";
            }

            Date now = new Date();

            if (now.getTime() - last.getTime() > 1000 * 60 * 10) {
                return "1";
            } else {
                return "0";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }
    /**
     * 文件上传
     * @param req
     * @param multiReq
     */
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    public String uploadKybotFile(HttpServletRequest req, MultipartHttpServletRequest multiReq){
        MultipartFile mfile = multiReq.getFile("file");
        if(mfile == null){
            return "fail";
        }
        String filepath = basepath + mfile.getOriginalFilename();
        File file = new File(filepath);
        if(file.exists()){
            file.delete();
        }
        log.info("文件上传至"+filepath+",开始上传......");
        FileOutputStream fos = null;
        InputStream fs = null;
        try {
            fos = new FileOutputStream(file);
            fs = mfile.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = fs.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }
            fos.close();
            fs.close();
            log.info("文件上传完成.");

            //保存上传文件日志
            Map<String, Object> map = new HashMap<>();
            map.put("id",UUID.randomUUID().toString());
            map.put("remoteIp",req.getRemoteAddr());
            map.put("remoteHost",req.getRemoteHost());
            map.put("zipName",file.getName());
            map.put("zipSize",file.getTotalSpace());
            map.put("filePath",file.getAbsolutePath());
            map.put("upTime",new Date());
            zipFileService.saveZipFile(map);

            //执行分析包数据读取
            kylinAnalysis.exec(file);

            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return "fail";
        }finally {
            try {
                if(fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fs != null)
                    fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
